<template>
  <div>
    <!-- 面包屑区域 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片区域 -->
    <el-card>
      <!-- 搜索与添加区域 -->
      <el-row :gutter="20">
        <el-col :span="8">
          <el-input placeholder="请输入内容" v-model="queryInfo.query" clearable @clear='getUserList' @change='getUserList'>
            <el-button slot="append" icon="el-icon-search" @click="getUserList"></el-button>
          </el-input>
        </el-col>
        <el-col :span="4">
          <el-button type="primary" @click="dialogVisible=true">添加用户</el-button>
        </el-col>
      </el-row>
      <!-- 用户列表区域 -->
      <el-table :data="userlist" stripe border style="width: 100%">
        <el-table-column type="index" label="序号"></el-table-column>
        <el-table-column prop="username" label="姓名" min-width="180px">
        </el-table-column>
        <el-table-column prop="email" label="邮箱" min-width="180px">
        </el-table-column>
        <el-table-column prop="mobile" label="电话" min-width="180px">
        </el-table-column>
        <el-table-column prop="role_name" label="角色" min-width="180px">
        </el-table-column>
        <el-table-column label="状态" min-width="180px">
          <template v-slot:default='scope'>
            <!-- {{scope.row}} -->
            <el-switch v-model="scope.row.mg_state" active-color="#13ce66" inactive-color="#ff4949" @change="stateChange(scope.row)">
            </el-switch>
          </template>
        </el-table-column>
        <el-table-column label="操作" min-width="180px">
          <template v-slot:default='scope'>
            <!-- 修改按钮 -->
            <el-button type="primary" icon="el-icon-edit" size="mini" @click="showModifyDialog(scope.row.id)"></el-button>
            <!-- 删除按钮 -->
            <el-button type="danger" icon="el-icon-delete" size="mini" @click="removeUser(scope.row.id)"></el-button>
            <!-- 分配角色按钮 -->
            <el-tooltip effect="dark" content="分配角色" placement="top" :enterable="false">
              <el-button type="warning" icon="el-icon-setting" size="mini" @click="setRole(scope.row)"></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
      <!-- 页码区域 -->
      <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page="queryInfo.pagenum" :page-sizes="[1, 2, 3, 5, 10]" :page-size="queryInfo.pagesize" layout="total, sizes, prev, pager, next, jumper" :total="total">
      </el-pagination>
      <!-- 添加用户区域 -->
      <el-dialog title="添加用户" :visible.sync="dialogVisible" width="50%" @close="resetForm">
        <!-- 内容区 -->
        <el-form ref="addFormRef" :model="add_form" :rules="rules" label-width="80px">
          <el-form-item label="用户名" prop="username">
            <el-input v-model="add_form.username"></el-input>
          </el-form-item>
          <el-form-item label="密码" prop="password">
            <el-input v-model="add_form.password"></el-input>
          </el-form-item>
          <el-form-item label="邮箱" prop="email">
            <el-input v-model="add_form.email"></el-input>
          </el-form-item>
          <el-form-item label="手机" prop="mobile">
            <el-input v-model="add_form.mobile"></el-input>
          </el-form-item>
        </el-form>
        <!-- 按钮区 -->
        <span slot="footer" class="dialog-footer">
          <el-button @click="dialogVisible = false">取 消</el-button>
          <el-button @click="resetForm">重置</el-button>
          <el-button type="primary" @click="addUser">确 定</el-button>
        </span>
      </el-dialog>
      <!-- 修改用户信息区域 -->
      <el-dialog title="修改用户信息" :visible.sync="dialogModifyVisible" width="50%" @close="resetModifyForm">
        <el-form ref="modifyFormRef" :model="modify_form" :rules="rules" label-width="80px">
          <el-form-item label="用户名">
            <el-input v-model="modify_form.username" disabled></el-input>
          </el-form-item>
          <el-form-item label="邮箱" prop="email">
            <el-input v-model="modify_form.email"></el-input>
          </el-form-item>
          <el-form-item label="手机" prop="mobile">
            <el-input v-model="modify_form.mobile"></el-input>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="dialogModifyVisible = false">取 消</el-button>
          <el-button @click="resetModifyForm">重置</el-button>
          <el-button type="primary" @click="modifyUser">确 定</el-button>
        </div>
      </el-dialog>
      <!-- 分配角色区域 -->
      <el-dialog title="分配角色" :visible.sync="dialogSetRoleVisible" width="50%" @close="resetSetRole">
        <div>
          <p>当前的用户：{{userInfo.username}}</p>
          <p>当前的角色：{{userInfo.role_name}}</p>
          <p>分配新角色：
            <el-select v-model="selectedRoleID" placeholder="请选择">
              <el-option v-for="item in roleslist" :key="item.id" :label="item.roleName" :value="item.id">
              </el-option>
            </el-select>
          </p>
        </div>
        <div slot="footer" class="dialog-footer">
          <el-button @click="dialogSetRoleVisible = false">取 消</el-button>
          <el-button type="primary" @click="saveRoleinfo">确 定</el-button>
        </div>
      </el-dialog>
    </el-card>
  </div>
</template>

<script>
export default {
  name: 'MyUsers',
  data() {
    // 验证邮箱的规则
    const checkEmail = (rule, value, cb) => {
      // 验证邮箱的正则表达式
      const regEmail = /^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+(\.[a-zA-Z0-9_-])+/
      if (regEmail.test(value)) {
        // 合法的邮箱
        return cb()
      }
      cb(new Error('请输入合法的邮箱'))
    }
    // 验证手机号的规则
    const checkMobile = (rule, value, cb) => {
      // 验证手机号的正则表达式
      const regMobile = /^(0|86|17951)?(13[0-9]|15[012356789]|17[678]|18[0-9]|14[57])[0-9]{8}$/
      if (regMobile.test(value)) {
        return cb()
      }
      cb(new Error('请输入合法的手机号'))
    }

    return {
      queryInfo: {
        query: '',
        // 当前的页数
        pagenum: 1,
        // 当前每页显示多少条数据
        pagesize: 3
      },
      userlist: [],
      roleslist: [],
      total: 0,
      dialogVisible: false,
      dialogModifyVisible: false,
      dialogSetRoleVisible: false,
      add_form: {
        username: '',
        password: '',
        email: '',
        mobile: ''
      },
      modify_form: {},
      userInfo: {},
      // 选中的新的角色id
      selectedRoleID: '',
      rules: {
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
          { min: 1, max: 10, message: '长度在 1 到 10 个字符', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          { min: 3, max: 15, message: '长度在 3 到 15 个字符', trigger: 'blur' }
        ],
        email: [
          { required: true, message: '请输入邮箱', trigger: 'blur' },
          { validator: checkEmail, trigger: 'blur' }
        ],
        mobile: [
          { required: true, message: '请输入手机号', trigger: 'blur' },
          { validator: checkMobile, trigger: 'blur' }
        ]
      }
    }
  },
  created() {
    this.getUserList()
  },
  methods: {
    // 获取用户列表
    async getUserList() {
      const { data: res } = await this.$http.get('/users', { params: this.queryInfo })
      // console.log(res)
      if (res.meta.status !== 200) {
        return this.$message.error('获取用户列表失败！')
      }
      this.userlist = res.data.users
      this.total = res.data.total
    },
    // 监听 pagesize 改变的事件
    handleSizeChange(val) {
      // console.log(`每页 ${val} 条`)
      this.queryInfo.pagesize = val
      this.getUserList()
    },
    // 监听 pagenum页码值 改变的事件
    handleCurrentChange(val) {
      // console.log(`当前页在第 ${val} 页`)
      this.queryInfo.pagenum = val
      this.getUserList()
    },
    async stateChange(userInfo) {
      // console.log(userInfo)
      const { data: res } = await this.$http.put('/users/' + userInfo.id + '/state/' + userInfo.mg_state)
      if (res.meta.status !== 200) {
        userInfo.mg_state = !userInfo.mg_state
        return this.$message.error('更新状态失败！')
      }
      this.$message.success('更新状态成功！')
    },
    // 重置添加用户表单
    resetForm() {
      this.$refs.addFormRef.resetFields()
    },
    // 添加用户预验证
    addUser() {
      this.$refs.addFormRef.validate(async valid => {
        if (!valid) return
        const { data: res } = await this.$http.post('/users', this.add_form)
        if (res.meta.status !== 201) {
          return this.$message.error('添加用户失败')
        }
        this.$message.success('添加用户成功')
        this.dialogVisible = false
        this.getUserList()
      })
    },
    // 根据id查询用户信息
    async showModifyDialog(id) {
      this.dialogModifyVisible = true
      // console.log(id)
      const { data: res } = await this.$http.get('/users/' + id)
      // console.log(res)
      if (res.meta.status !== 200) return
      this.modify_form = res.data
    },
    // 重置修改用户信息表单
    resetModifyForm() {
      this.$refs.modifyFormRef.resetFields()
    },
    // 修改用户信息预验证
    modifyUser() {
      this.$refs.modifyFormRef.validate(async valid => {
        if (!valid) return
        const { data: res } = await this.$http.put('/users/' + this.modify_form.id, { email: this.modify_form.email, mobile: this.modify_form.mobile })
        if (res.meta.status !== 200) {
          return this.$message.error('修改用户信息失败')
        }
        this.dialogModifyVisible = false
        this.getUserList()
        this.$message.success('修改用户信息成功')
      })
    },
    // 删除用户信息
    removeUser(id) {
      // 弹框提示
      this.$confirm('此操作将永久删除该用户, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(async() => {
          const { data: res } = await this.$http.delete('/users/' + id)
          if (res.meta.status === 200) {
            this.$message({
              type: 'success',
              message: '删除成功!'
            })
          }
          this.getUserList()
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        })
    },
    // 显示分配角色区域
    async setRole(userInfo) {
      this.dialogSetRoleVisible = true
      this.userInfo = userInfo
      // console.log(userInfo)
      // 获取角色列表
      const { data: res } = await this.$http.get('/roles')
      if (res.meta.status !== 200) {
        return this.$message.error('获取角色列表失败！')
      }
      this.roleslist = res.data
    },
    // 保存分配的新角色
    async saveRoleinfo() {
      this.dialogSetRoleVisible = false
      if (!this.selectedRoleID) {
        return this.$message.error('请选择要分配的角色！')
      }
      const { data: res } = await this.$http.put('/users/' + this.userInfo.id + '/role', { rid: this.selectedRoleID })
      if (res.meta.status !== 200) {
        return this.$message.error('分配角色失败！')
      }
      this.$message.success('分配角色成功！')
      this.getUserList()
    },
    resetSetRole() {
      this.selectedRoleID = ''
      this.userInfo = {}
    }
  }
}
</script>

<style lang='less' scoped>
</style>
